package com.wnhoo.smartfishtank.api.other;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.ParseException;

import org.apache.http.HttpEntity;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * Created by kevinwen on 2014/11/12.
 * Copyright (c) 2014/11/12.KevinWen. All rights reserved.
 */
public class JSONUtil {


    /**
     * 这个类作用是在做Http请求的时候把返回来的HttpEntity解析为JSONObject或者是JSONArray类型的数据
     */

    public static String tag = "JSONUtil";

    private static String init(HttpEntity entity) throws IOException {
        InputStream inputStream = entity.getContent();
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
        String result = "";
        String line = "";
        //一行一行地读取数据
        while((line = reader.readLine())!= null){
            result = result + line;
        }
        //Log.d(tag,"JsonString result:"+result);
//		Constants.josnResult = result;
        return result;
    }
    /**
     * 从HttpEntity提取出JSONString信息；
     */
    public static String getJSONString(HttpEntity entity)throws IOException{

        return init(entity);
    }

    /**
     * 从JSONString提取出JSONObject类型信息；
     * @throws ParseException
     */
    public static JSONObject getJsonObject(String result)throws IOException,JSONException{

        JSONObject josn = new JSONObject(result);
        return josn;
    }


    /**
     * 从HttpEntity提取出JSONObject类型信息；
     * @throws ParseException
     */
    public static JSONObject getJsonObject(HttpEntity entity)throws IOException,JSONException{
        String result = init(entity);
//		Log.d(tag,"JSON:"+result);
        JSONObject josn = new JSONObject(result);
        return josn;
    }



    /**
     * 从HttpEntity提取出JSONArray类型信息；
     * @throws IOException
     * @throws ParseException
     */
    public static JSONArray getJsonArray(HttpEntity entity) throws IOException, JSONException{
        String result = init(entity);
        JSONArray json = new JSONArray(result);
        return json;
    }

    /**
     * 从String提取出JSONArray类型信息；
     * @throws ParseException
     */
    public static JSONArray getJsonArray(String result) throws JSONException{
        JSONArray json = new JSONArray(result);
        return json;
    }



    public static JSONArray getJsonArray_get_data(HttpEntity entity) throws IOException, JSONException{
        String result = init(entity);
        JSONObject jsonObject = new JSONObject(result);
        JSONArray json = jsonObject.getJSONArray("data");
        return json;
    }
}
